package pro.shushi.pamirs.hr.core.helper;

import pro.shushi.pamirs.boot.base.model.*;
import pro.shushi.pamirs.hr.api.enums.HrSimpleExpEnum;
import pro.shushi.pamirs.meta.api.dto.config.ModelConfig;
import pro.shushi.pamirs.meta.api.session.PamirsSession;
import pro.shushi.pamirs.meta.base.common.MetaBaseModel;
import pro.shushi.pamirs.meta.common.exception.PamirsException;
import pro.shushi.pamirs.meta.domain.ModelData;

import java.util.Date;

/**
 * 元数据安装注册表帮助类
 *
 * @author shushi
 */
public class ModelDataHelper {

    private static final String DESIGNER_LOAD_MODULE = "k2";

    private ModelDataHelper() {
        //reject create object
    }

    public static ModelData convert(MetaBaseModel data) {
        return convert(data, null);
    }

    public static ModelData convert(MetaBaseModel data, String module) {
        if (data == null) {
            return null;
        } else if (data instanceof ViewAction) {
            return convertViewAction((ViewAction)data);
        } else if (data instanceof UrlAction) {
            // return convertUrlAction((UrlAction)data);
        } else if (data instanceof ServerAction) {
            return convertServerAction((ServerAction)data);
        } else if (data instanceof ClientAction) {
            // return convertClientAction((ClientAction)data);
        } else if (data instanceof Menu) {
            // return convertMenu((Menu)data);
        } else {
            throw PamirsException.construct(HrSimpleExpEnum.DATA_REL_META_NOSUPPORT_TYPE).errThrow();
        }

        return null;
    }

    private static ModelData convertViewAction(ViewAction data) {
        return generatorModelData(ViewAction.MODEL_MODEL, data)
                .setModule(data.getModule())
                .setLoadModule(data.getModule());
    }

    private static ModelData convertServerAction(ServerAction data) {
        ModelConfig modelConfig = PamirsSession.getContext().getModelConfig(data.getModel());
        return generatorModelData(ServerAction.MODEL_MODEL, data)
                .setModule(modelConfig.getModule())
                .setLoadModule(modelConfig.getModule());
    }

    private static <T extends MetaBaseModel> ModelData generatorModelData(String model, T data) {
        Date dateInit = data.getCreateDate();
        if (dateInit == null) {
            dateInit = new Date();
        }
        return new ModelData()
                .setLowCode(true)
                .setSource(data.getSystemSource())
                .setCode(ModelData.generateCode(model, data.getSign()))
                .setLoadModule(DESIGNER_LOAD_MODULE)
                .setModel(model)
                .setResId(data.getId())
                .setDateInit(dateInit)
                .setDateUpdate(new Date());
    }
}
